package com.mxnet.chongjin.supoman.fragment;


import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.github.barteksc.pdfviewer.PDFView;
import com.mxnet.chongjin.supoman.R;
import com.mxnet.chongjin.supoman.config.Api;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * A simple {@link Fragment} subclass.
 */
public class InstructionFragment extends Fragment {
    private Context mContext;
    private PDFView mTextView;
    private Bundle mBundle;

    public InstructionFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_instruction, container, false);
        mContext = getContext();
        initView(view);
        return view;
    }

    private void initView(View v) {
        mTextView = v.findViewById(R.id.tv_instruction);
        mBundle = getArguments();
        if (mBundle.getString("book") != null) {
            final String bookUrl = mBundle.getString("book");
            new Thread() {
                public void run() {
                    try {
                        URL url = new URL(Api.URL_HEADER + Api.GET_IMAGE + bookUrl);
                        HttpURLConnection connection = (HttpURLConnection)
                                url.openConnection();
                        connection.setRequestMethod("GET");//试过POST 可能报错
                        connection.setDoInput(true);
                        connection.setConnectTimeout(10000);
                        connection.setReadTimeout(10000);
                        //实现连接
                        connection.connect();
                        if (connection.getResponseCode() == 200) {
                            InputStream is = connection.getInputStream();
                            //这里给过去就行了
                            mTextView.fromStream(is)
                                    .enableSwipe(true)
                                    .swipeHorizontal(false)
                                    .enableDoubletap(true)
                                    .enableAnnotationRendering(false)
                                    .password(null)
                                    .scrollHandle(null)
                                    .load();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        } else {
            
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mTextView = null;
        mBundle = null;
    }
}
